import * as Data from './maps'
export default class GameInfo {
  constructor() {
    this.level = 0
    this.step = 0
    this.minStep = 0
    this.isFinished = false
    this.bestStep = null
  }

  renderGameInfo(ctx) {
    ctx.fillStyle = '#000000'
    ctx.font = '20px Arial'

    ctx.fillText(`第${this.level+1}关`, 20, 70)
    ctx.fillText(`步数：${this.step} / (${this.minStep})`, 150, 70)
    if (this.bestStep) {
      let score = '普通'
      if (this.bestStep <= this.minStep) {
        score = '完美'
      } else {
        let delta = this.bestStep - this.minStep
        let rate = delta / this.minStep
        if (rate <= 0.1 || delta == 1) {
          score = '杰出'
        } else if (rate <= 0.3 || delta <= 2) {
          score = '优秀'
        }
      }
      ctx.fillText(`历史最佳：${this.bestStep} (${score})`, 20, 120)
    } else {
      ctx.fillText(`历史最佳：--`, 20, 120)
    }
  }

  setLevel(level) {
    if (level || level == 0) {
      this.level = level
    } else {
      var value = wx.getStorageSync('level')
      if (value) {
        try {
          this.level = parseInt(value)
        } catch (error) {
          this.level = 0
        }
        if (this.level < 0) {
          this.level = 0
        }
        if (this.level > Data.maps.length - 1) {
          this.level = Data.maps.length - 1
        }
      }
    }
    wx.setStorageSync('level', this.level)
    let map = Data.maps[this.level]
    let data = map.split(';')
    this.minStep = parseInt(data[1])
    this.mapData = data[0]
    this.isFinished = false
    this.step = 0
    this.getInfo()
  }

  nextLevel() {
    if (!this.bestStep) {
      return false
    }
    if (this.level < Data.maps.length - 1) {
      this.setLevel(this.level + 1)
      return true
    }
    return false
  }
  prevLevel() {
    if (this.level > 0) {
      this.setLevel(this.level - 1)
      return true
    }
    return false
  }

  finish() {
    this.isFinished = true
    if (this.bestStep) {
      if (this.step >= this.bestStep) {
        return
      }
    }
    this.bestStep = this.step
    wx.setStorageSync(`level_bs_${this.level}`, this.bestStep)
  }

  getInfo() {
    var bestStep = wx.getStorageSync(`level_bs_${this.level}`)
    if (bestStep) {
      try {
        this.bestStep = parseInt(bestStep)
      } catch (error) {
        this.bestStep = null
      }
    } else {
      this.bestStep = null
    }
  }
}